#!/bin/bash

# this scripts returns current total traffic.

VARIABLES=(`perl $TWMFOLDER/bin/get_varMultipleValue.pl grep gawk sed iptables ifconfig _DEFAULT_`)
grep=${VARIABLES[0]}
gawk=${VARIABLES[1]}
sed=${VARIABLES[2]}
iptables=${VARIABLES[3]}
ifconfig=${VARIABLES[4]}

interfaces=(`perl $TWMFOLDER/bin/get_varISP.pl`)
ext_interfaces=()
for item in ${interfaces[*]}
do
       intf=(`echo $item | $sed -e "s/:/ /g"`)
       if [ "${intf[3]}" = "1" ]; then
               local_interface=${intf[0]}
       else
               ext_interfaces[${#ext_interfaces[*]}]=${intf[0]}
       fi
       if [ "${intf[4]}" = "1" ]; then
               default_isp_interface=${intf[0]}
       fi
       if [ "${intf[5]}" != "0x12" ]; then # What does it means '0x12' ??
               route_interfaces="$route_interfaces ${intf[0]}:${intf[6]}"
       fi
done

$iptables -xvn -L FORWARD | $grep all | $grep $local_interface | $gawk '{ print $2 "\t" $8"-->" "\t" "default_isp_interface" "\t" "FORWARD"}' | $sed -e "s/default_isp_interface/$default_isp_interface/" 2>/dev/null
$iptables -xvn -L OUTPUT | $grep all | $gawk '{ print $2 "\t" "-->"$9 "\t" "default_isp_interface" "\t" "OUTPUT"}' | $sed -e "s/default_isp_interface/$default_isp_interface/" 2>/dev/null
$iptables -xvn -L INPUT | $grep all | $grep $local_interface | $gawk '{ print $2 "\t" $8"-->" "\t" "default_isp_interface" "\t" "INPUT"}' | $sed -e "s/default_isp_interface/$default_isp_interface/" 2>/dev/null

SQUID_PORTS=(`perl $TWMFOLDER/modules/http_logging/get_squid_data.pl`)
for item in ${SQUID_PORTS[*]}
do
       echo $item | $sed -e "s/:/ /g" | while read port extif other; do
               $iptables -xvn -L INPUT | $grep "tcp dpt:$port" | $gawk '{ print $2 "\t" $8"-->" "\t" "isp_interface" "\t" "INPUT_"$11}' | $sed -e "s/isp_interface/$extif/" 2>/dev/null
               $iptables -xvn -L OUTPUT | $grep "tcp spt:$port" | $gawk '{ print $2 "\t" "-->"$9 "\t" "isp_interface" "\t" "OUTPUT_"$11}' | $sed -e "s/isp_interface/$extif/" 2>/dev/null
       done
done


for item in ${route_interfaces[*]}
do
       echo $item | $sed -e "s/:/ /g" | while read extif msc ; do
               $iptables -xvn -L FORWARD | $grep all | $grep $extif | $gawk '{ print $2 "\t" "-->"$9 "\t" $6 "\t" "FORWARD"}'
               $iptables -t mangle -xvn -L PREROUTING | $grep "MARK set $msc" | $gawk '{print $2 "\t" $8"-->" "\t" "ext" "\t" "mangle_MARK_PREROUTING_"$11}' | $sed -e "s/ext/$extif/" 2>/dev/null
               $iptables -t nat -xvn -L POSTROUTING | $grep $extif | $gawk '{ print $2 "\t" $8"-->" "\t" $7 "\t" "MASQUERADE"}' | $sed -e "s/$extif/$extif/" 2>/dev/null
       done
done

$iptables -t mangle -Z
$iptables -t nat -Z
$iptables -Z

exit 0

